// 添加点击效果和活动状态
document.addEventListener('DOMContentLoaded', function () {
    // 导航项点击效果
    const navLinks = document.querySelectorAll('.traditional-pills .nav-link');

    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            // 移除所有active类
            navLinks.forEach(item => {
                item.classList.remove('active');
            });

            // 为当前点击项添加active类
            this.classList.add('active');

            // 添加点击反馈
            this.style.transform = 'translateY(2px)';
            setTimeout(() => {
                this.style.transform = '';
            }, 200);
        });
    });

    // 搜索框交互
    const searchInput = document.querySelector('.search-input');
    const searchBtn = document.querySelector('.search-btn');

    searchBtn.addEventListener('click', function () {
        if (searchInput.value.trim() !== '') {
            // 执行搜索操作
            searchProducts(searchInput.value);

            // 添加点击反馈
            this.style.transform = 'translateY(2px)';
            setTimeout(() => {
                this.style.transform = '';
            }, 200);
        }
    });

    // 回车键搜索
    searchInput.addEventListener('keypress', function (e) {
        if (e.key === 'Enter' && this.value.trim() !== '') {
            searchProducts(this.value);
        }
    });

    // 实时搜索
    searchInput.addEventListener('input', function () {
        if (this.value.trim() !== '') {
            searchProducts(this.value);
        } else {
            const firstTab = document.querySelector('.nav-link.active[data-bs-toggle="pill"]');
            if (firstTab) {
                const targetId = firstTab.getAttribute('href').substring(1);
                loadProducts(targetId);
            }
        }
    });

    // 购物车相关功能
    let cart = [];
    const cartCountElement = document.querySelector('.cart-count');

    // 初始化购物车数量
    updateCartCount();

    // 添加商品到购物车
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('add-to-cart')) {
            const productId = e.target.dataset.productId;
            addToCart(productId);
        }
    });

    // 添加到购物车函数
    function addToCart(productId) {
        fetch('/api/cart', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                product_id: productId,
                quantity: 1
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateCartCount();
                    alert('商品已添加到购物车！');
                } else {
                    alert('添加商品失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('添加购物车错误:', error);
                alert('添加商品失败，请稍后重试');
            });
    }

    // 更新购物车数量显示
    function updateCartCount() {
        fetch('/api/cart/count')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    cartCountElement.textContent = data.count;
                }
            })
            .catch(error => {
                console.error('获取购物车数量失败:', error);
            });
    }

    // 初始化加载第一个选项卡的内容
    const firstTab = document.querySelector('.nav-link.active[data-bs-toggle="pill"]');
    if (firstTab) {
        const targetId = firstTab.getAttribute('href').substring(1);
        loadProducts(targetId);
    }

    // 监听选项卡切换
    document.querySelectorAll('.nav-link[data-bs-toggle="pill"]').forEach(link => {
        link.addEventListener('shown.bs.tab', function(e) {
            const targetId = e.target.getAttribute('href').substring(1);
            loadProducts(targetId);
        });
    });
});

/*拍照识别物体*/
// 打开摄像头
function openCamera() {
    const modal = document.getElementById('cameraModal');
    modal.style.display = 'block';

    // 初始化摄像头
    const video = document.getElementById('cameraPreview');

    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(function (stream) {
                video.srcObject = stream;
            })
            .catch(function (error) {
                console.error("摄像头访问错误:", error);
                alert("无法访问摄像头，请确保已授予摄像头权限");
            });
    } else {
        alert("您的浏览器不支持摄像头访问");
    }
}

// 关闭摄像头
function closeCamera() {
    const modal = document.getElementById('cameraModal');
    modal.style.display = 'none';

    // 关闭摄像头流
    const video = document.getElementById('cameraPreview');
    if (video.srcObject) {
        video.srcObject.getTracks().forEach(track => track.stop());
    }

    // 隐藏识别结果
    document.getElementById('recognitionResult').style.display = 'none';
}

// 拍照识别
document.getElementById('takePhotoBtn').addEventListener('click', function () {
    const video = document.getElementById('cameraPreview');
    const canvas = document.getElementById('cameraCanvas');
    const context = canvas.getContext('2d');

    // 设置canvas尺寸与视频相同
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    // 拍照
    context.drawImage(video, 0, 0, canvas.width, canvas.height);

    // 这里应该是调用图像识别API的地方
    // 模拟识别过程
    setTimeout(function () {
        // 模拟识别结果
        const objects = ['青花瓷茶壶', '紫砂壶', '文房四宝', '檀香扇', '龙井茶叶'];
        const randomObject = objects[Math.floor(Math.random() * objects.length)];
        document.getElementById('recognizedObject').textContent = randomObject;

        // 显示识别结果
        document.getElementById('recognitionResult').style.display = 'block';

        // 模拟1秒后自动搜索
        setTimeout(function () {
            document.querySelector('.search-input').value = randomObject;
            closeCamera();
            // 这里可以触发搜索
            searchProducts(randomObject);
        }, 1000);
    }, 1500);
});

// 点击模态框外部关闭
window.onclick = function (event) {
    if (event.target == document.getElementById('cameraModal')) {
        closeCamera();
    }
}

// 搜索选项切换
document.querySelectorAll('.search-option').forEach(option => {
    option.addEventListener('click', function () {
        document.querySelectorAll('.search-option').forEach(opt => {
            opt.classList.remove('active');
        });
        this.classList.add('active');
    });
});

function loadProducts(category, page = 1) {
    const loadingText = {
        'v-pills-home': '正在加载火爆热卖商品...',
        'v-pills-profile': '正在加载猜你喜欢商品...',
        'v-pills-messages': '正在加载特别活动商品...',
        'v-pills-clothing': '正在加载服饰织物商品...',
        'v-pills-bags': '正在加载非遗包袋商品...',
        'v-pills-shoe': '正在加载手工鞋类商品...',
        'v-pills-gourmet': '正在加载非遗食饮商品...',
        'v-pills-ornaments': '正在加载非遗饰品商品...',
        'v-pills-homeware': '正在加载家居用品商品...',
        'v-pills-art1': '正在加载非遗包袋商品...',
        'v-pills-art2': '正在加载艺术摆件商品...',
        'v-pills-musical': '正在加载非遗乐器商品...'
    };

    const tabPane = document.getElementById(category);
    if (!tabPane) return;

    tabPane.innerHTML = `<p>${loadingText[category] || '正在加载商品...'}</p>`;

    // 映射分类到API参数
    const categoryMap = {
        'v-pills-home': 'hot',
        'v-pills-profile': 'recommended',
        'v-pills-messages': 'special',
        'v-pills-clothing': '服饰织物',
        'v-pills-bags': '非遗包袋',
        'v-pills-shoe': '手工鞋类',
        'v-pills-gourmet': '非遗食饮',
        'v-pills-ornaments': '非遗饰品',
        'v-pills-homeware': '家居用品',
        'v-pills-art1': '非遗包袋',
        'v-pills-art2': '艺术摆件',
        'v-pills-musical': '非遗乐器'
    };

    const apiCategory = categoryMap[category] || '';
    fetch(` http://127.0.0.1:5000`)
   // fetch(`http://localhost:5000/api/products?category=${apiCategory}&page=${page}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.data.length > 0) {
                renderProducts(tabPane, data.data, category);
                updatePagination(data.pagination, category);
            } else {
                tabPane.innerHTML = '<p>暂无商品数据</p>';
            }
        })
        .catch(error => {
            console.error('加载商品失败:', error);
            tabPane.innerHTML = '<p>加载商品失败，请稍后重试</p>';
        });
}

// 渲染商品卡片
function renderProducts(container, products, category) {
    let html = '<div class="container"><div class="row row-cols-1 row-cols-md-3 g-4">';

    products.forEach(product => {
        html += `
                <div class="col">
                    <div class="card h-100">
                        ${product.price < 150 ? '<div class="card-tag">特惠</div>' : ''}
                        <img class="card-img-top" src="${product.image_url}" alt="${product.name}">
                        <div class="card-body text-center">
                            <p class="card-title"><a href="商品信息.html?id=${product.id}">${product.name}</a></p>
                            <p class="price">¥${product.price.toFixed(2)}</p>
                            <a href="商品信息.html?id=${product.id}"><button class="btn btn-classic">了解详情</button></a>
                            <button class="btn btn-primary add-to-cart" data-product-id="${product.id}">加入购物车</button>
                        </div>
                    </div>
                </div>
            `;
    });

    html += '</div></div>';
    container.innerHTML = html;
}

// 更新分页控件
function updatePagination(pagination, category) {
    const paginationContainer = document.querySelector('.pagination');
    let html = '';

    // 上一页按钮
    if (pagination.has_prev) {
        html += `<li class="page-item"><a class="page-link" href="#" data-page="${pagination.prev_page}" data-category="${category}">上一页</a></li>`;
    }

    // 页码按钮
    for (let i = 1; i <= pagination.total_pages; i++) {
        html += `<li class="page-item ${i === pagination.current_page ? 'active' : ''}">
            <a class="page-link" href="#" data-page="${i}" data-category="${category}">${i}</a>
        </li>`;
    }

    // 下一页按钮
    if (pagination.has_next) {
        html += `<li class="page-item"><a class="page-link" href="#" data-page="${pagination.next_page}" data-category="${category}">下一页</a></li>`;
    }

    paginationContainer.innerHTML = html;

    // 添加分页点击事件
    document.querySelectorAll('.page-link').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const page = parseInt(this.dataset.page);
            const category = this.dataset.category;
            loadProducts(category, page);
        });
    });
}

// 搜索商品
function searchProducts(query) {
    const mainContent = document.querySelector('.main-content');
    mainContent.innerHTML = '<p>正在搜索商品...</p>';

    fetch(`http://localhost:5000/api/products?search=${query}`)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.data.length > 0) {
                const tabPane = document.createElement('div');
                renderProducts(tabPane, data.data, 'search-results');
                mainContent.innerHTML = tabPane.innerHTML;
            } else {
                mainContent.innerHTML = '<p>未找到相关商品</p>';
            }
        })
        .catch(error => {
            console.error('搜索商品失败:', error);
            mainContent.innerHTML = '<p>搜索商品失败，请稍后重试</p>';
        });
}